import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class PageItem {
  final String name;
  final String path;

  PageItem({required this.name, required this.path});
}

class HomePage extends StatelessWidget {
  List pageList = [
    PageItem(name: "FirstDemo", path: "/firstDemo"),
    PageItem(name: "BoxPage", path: "/boxPage"),
    PageItem(name: "CommonPage", path: "/commonPage"),
    PageItem(name: "ImageListPage", path: "/imageListPage"),
    PageItem(name: "WeChatPayPage", path: "/weChatPayPage"),
    PageItem(name: "LoginPage", path: "/loginPage"),
  ];

  HomePage({super.key});

  List<Row> buildRowList(context) {
    var newList = <List<PageItem>>[];
    var cacheList = <PageItem>[];
    for (var i = 0; i < pageList.length; i++) {
      if (cacheList.length == 3) {
        newList.add(cacheList);
        cacheList = <PageItem>[];
      }
      cacheList.add(pageList[i]);
      if (i == pageList.length - 1) {
        newList.add(cacheList);
      }
    }
    var rowList = <Row>[];
    for (var listItem in newList) {
      rowList.add(buildRowItem(context, listItem));
    }
    return rowList;
  }

  Row buildRowItem(context, List<PageItem> list) {
    Iterable<Container> children = list.map((item) {
      return Container(
        width: MediaQuery.of(context).size.width * 0.3333,
        color: Colors.blue,
        padding: const EdgeInsets.all(10),
        child: TextButton(
          style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(Colors.greenAccent)),
          onPressed: () {
            GoRouter.of(context).push(item.path);
          },
          child: Text(item.name),
        ),
      );
    });
    return Row(children: children.toList());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("首页", style: Theme.of(context).textTheme.headline3),
      ),
      body: Column(
        children: buildRowList(context),
      ),
    );
  }
}
